#include "server.h"

#include <QDebug>
#include "base.qpb.h"
#include "user.qpb.h"
#include "gateway.qpb.h"
#include "friend.qpb.h"
#include "file.qpb.h"
#include "message_storage.qpb.h"
#include "message_transmit.qpb.h"
#include "speech_recognition.qpb.h"
#include "notify.qpb.h"

#include <QDateTime>

/////////////////////////////////////////////////////////////////////////////////////
/// 一些辅助函数
/////////////////////////////////////////////////////////////////////////////////////

//生成一些默认的UserInfo对象
bite_im::UserInfo makeUserInfo(int index,const QByteArray& avatar){
    bite_im::UserInfo userInfo;
    userInfo.setUserId(QString::number(1000+index));
    userInfo.setNickname("张三" + QString::number(index));
    userInfo.setDescription("个性签名"+QString::number(index));
    userInfo.setPhone("18612345678");
    userInfo.setAvatar(avatar);
    return userInfo;
}

//生成一些默认的MessageInfo对象,文本消息
bite_im::MessageInfo makeTextMessageInfo(int index,const QString& chatSessionId,const QByteArray& avatar){
    bite_im::MessageInfo messageInfo;
    messageInfo.setMessageId(QString::number(3000 + index));
    messageInfo.setChatSessionId(chatSessionId);
    messageInfo.setTimestamp(getTime());
    messageInfo.setSender(makeUserInfo(index,avatar));


    bite_im::StringMessageInfo stringMessageInfo;
    stringMessageInfo.setContent("这是一条消息内容" + QString::number(index));

    bite_im::MessageContent messageContent;
    messageContent.setMessageType(bite_im::MessageTypeGadget::MessageType::STRING);
    messageContent.setStringMessage(stringMessageInfo);
    messageInfo.setMessage(messageContent);
    return messageInfo;
}

//图片消息
bite_im::MessageInfo makeImageMessageInfo(int index,const QString& chatSessionId,const QByteArray& avatar){
    bite_im::MessageInfo messageInfo;
    messageInfo.setMessageId(QString::number(3000 + index));
    messageInfo.setChatSessionId(chatSessionId);
    messageInfo.setTimestamp(getTime());
    messageInfo.setSender(makeUserInfo(index,avatar));

    bite_im::ImageMessageInfo imageMessageInfo;
    imageMessageInfo.setFileId("testImage");
    //真实服务器第一次推送,本身不带图片正文内容,只是推送fileId
    //需要通过fileId，二次发送请求,通过getSingleFile接口来获取到内容
    //imageMessageInfo.setImageContent();

    bite_im::MessageContent messageContent;
    messageContent.setMessageType(bite_im::MessageTypeGadget::MessageType::IMAGE);
    messageContent.setImageMessage(imageMessageInfo);
    messageInfo.setMessage(messageContent);
    return messageInfo;
}

//文件消息
bite_im::MessageInfo makeFileMessageInfo(int index,const QString& chatSessionId,const QByteArray& avatar){
    bite_im::MessageInfo messageInfo;
    messageInfo.setMessageId(QString::number(3000 + index));
    messageInfo.setChatSessionId(chatSessionId);
    messageInfo.setTimestamp(getTime());
    messageInfo.setSender(makeUserInfo(index,avatar));

    bite_im::FileMessageInfo fileMessageInfo;
    fileMessageInfo.setFileId("testFile");
    //真实服务器第一次推送,本身不带图片正文内容,只是推送fileId
    //需要通过fileId，二次发送请求,通过getSingleFile接口来获取到内容
    fileMessageInfo.setFileName("test.txt");
    //设置文件大小
    fileMessageInfo.setFileSize(10);

    bite_im::MessageContent messageContent;
    messageContent.setMessageType(bite_im::MessageTypeGadget::MessageType::FILE);
    messageContent.setFileMessage(fileMessageInfo);
    messageInfo.setMessage(messageContent);
    return messageInfo;
}

//语音消息
bite_im::MessageInfo makeSpeechMessageInfo(int index,const QString& chatSessionId,const QByteArray& avatar){
    bite_im::MessageInfo messageInfo;
    messageInfo.setMessageId(QString::number(3000 + index));
    messageInfo.setChatSessionId(chatSessionId);
    messageInfo.setTimestamp(getTime());
    messageInfo.setSender(makeUserInfo(index,avatar));

    bite_im::SpeechMessageInfo speechMessageInfo;
    speechMessageInfo.setFileId("testSpeech");
    //真实服务器第一次推送,本身不带图片正文内容,只是推送fileId
    //需要通过fileId，二次发送请求,通过getSingleFile接口来获取到内容

    bite_im::MessageContent messageContent;
    messageContent.setMessageType(bite_im::MessageTypeGadget::MessageType::SPEECH);
    messageContent.setSpeechMessage(speechMessageInfo);
    messageInfo.setMessage(messageContent);
    return messageInfo;
}

/////////////////////////////////////////////////////////////////////////////////////
/// HTTP 服务器
/////////////////////////////////////////////////////////////////////////////////////

//初始化instance
HttpServer* HttpServer::instance = nullptr;

//获取实例
HttpServer* HttpServer::getInstance(){
    if(instance == nullptr){
        instance = new HttpServer();
    }
    return instance;
}

//初始化httpServer(http服务器)-->绑定端口,配置路由......
bool HttpServer::init()
{
    //绑定端口-->此时返回的值是int,表示成功绑定端口号的数值
    int ret = httpServer.listen(QHostAddress::Any,8000);
    //配置路由-->此处的"路由"是web开发术语,和IP协议中没有任何关系,这里的路由是定义请求的路径和对应的处理函数之间的映射关系-->
    httpServer.route("/ping",[](const QHttpServerRequest& req){
        (void) req;
        qDebug() << "[http] 收到ping请求";
        return "pong";
    });
    //添加新的路由-->获取用户个人信息
    httpServer.route("/service/user/get_user_info",[=](const QHttpServerRequest& req){  //lambel表达式参数是接收到的请求,返回值是QHttpServerResponse对象
        return this->getUserInfo(req);
    });
    //添加新路由-->获取好友列表
    httpServer.route("/service/friend/get_friend_list",[=](const QHttpServerRequest& req){
        return this->getFriendList(req);
    });
    //添加新路由-->获取会话列表
    httpServer.route("/service/friend/get_chat_session_list",[=](const QHttpServerRequest& req){
        return this->getChatSessionList(req);
    });
    //添加新路由-->获取好友申请列表
    httpServer.route("/service/friend/get_pending_friend_events",[=](const QHttpServerRequest& req){
        return this->getApplyList(req);
    });
    //添加新路由-->获取指定会话的最近历史消息列表
    httpServer.route("/service/message_storage/get_recent",[=](const QHttpServerRequest& req){
        return this->getRecent(req);
    });
    //添加新路由-->处理从客户端发送消息
    httpServer.route("/service/message_transmit/new_message",[=](const QHttpServerRequest& req){
        return this->newMessage(req);
    });
    //添加新路由-->处理修改个人信息的昵称
    httpServer.route("/service/user/set_nickname",[=](const QHttpServerRequest& req){
        return this->setNickname(req);
    });
    //添加新路由-->处理修改个人信息的个性签名
    httpServer.route("/service/user/set_description",[=](const QHttpServerRequest& req){
        return this->setDescription(req);
    });
    //添加新路由-->处理获取短信验证码
    httpServer.route("/service/user/get_phone_verify_code",[=](const QHttpServerRequest& req){
        return this->getPhoneVerifyCode(req);
    });
    //添加新路由-->处理修改手机号
    httpServer.route("/service/user/set_phone",[=](const QHttpServerRequest& req){
        return this->setPhone(req);
    });
    //添加新路由-->处理修改头像
    httpServer.route("/service/user/set_avatar",[=](const QHttpServerRequest& req){
        return this->setAvatar(req);
    });
    //添加新路由-->处理删除好友
    httpServer.route("/service/friend/remove_friend",[=](const QHttpServerRequest& req){
        return this->removeFriend(req);
    });
    //添加新路由-->处理添加好友申请
    httpServer.route("/service/friend/add_friend_apply",[=](const QHttpServerRequest& req){
        return this->addFriendApply(req);
    });
    //添加新路由-->对添加好友申请的处理
    httpServer.route("/service/friend/add_friend_process",[=](const QHttpServerRequest& req){
        return this->addFriendProcess(req);
    });
    //添加新路由-->处理创建会话申请
    httpServer.route("/service/friend/create_chat_session",[=](const QHttpServerRequest& req){
        return this->createChatSession(req);
    });
    //添加新路由-->获取会话成员列表
    httpServer.route("/service/friend/get_chat_session_member",[=](const QHttpServerRequest& req){
        return this->getChatSessionMember(req);
    });
    //添加新路由-->获取搜索用户结果
    httpServer.route("/service/friend/search_friend",[=](const QHttpServerRequest& req){
        return this->searchFriend(req);
    });
    //添加新路由-->获取搜索历史消息结果
    httpServer.route("/service/message_storage/search_history",[=](const QHttpServerRequest& req){
        return this->searchHistory(req);
    });
    //添加新路由-->按时间获取搜索历史消息结果
    httpServer.route("/service/message_storage/get_history",[=](const QHttpServerRequest& req){
        return this->getHistory(req);
    });
    //添加新路由-->用户名登录请求
    httpServer.route("/service/user/username_login",[=](const QHttpServerRequest& req){
        return this->usernameLogin(req);
    });
    //添加新路由-->用户名注册请求
    httpServer.route("/service/user/username_register",[=](const QHttpServerRequest& req){
        return this->usernameRegister(req);
    });
    //添加新路由-->电话登录请求
    httpServer.route("/service/user/phone_login",[=](const QHttpServerRequest& req){
        return this->phoneLogin(req);
    });
    //添加新路由-->电话注册请求
    httpServer.route("/service/user/phone_register",[=](const QHttpServerRequest& req){
        return this->phoneRegister(req);
    });
    //添加新路由-->获取单个文件
    httpServer.route("/service/file/get_single_file",[=](const QHttpServerRequest& req){
        return this->getSingleFile(req);
    });
    //添加新路由-->语音转文字
    httpServer.route("/service/speech/recognition",[=](const QHttpServerRequest& req){
        return this->recognition(req);
    });
    return ret == 8000;
}

//获取个人用户信息
QHttpServerResponse HttpServer::getUserInfo(const QHttpServerRequest &req)
{
    //1.解析请求,把body取出来,并且通过pd进行反序列化
    bite_im::GetUserInfoReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG() << "[REQ 获取用户信息] requestId=" << pbReq.requestId() << ",loginSessionId=" << pbReq.sessionId();
    //2.构造响应数据
    bite_im::GetUserInfoRsp pbResq;
    pbResq.setRequestId(pbReq.requestId());
    pbResq.setSuccess(true);
    pbResq.setErrmsg("");

    bite_im::UserInfo userInfo;
    userInfo.setUserId("1029"); //调整自己的用户id,和返回的消息列表的内容(消息发送者)匹配上
    userInfo.setNickname("梦境");
    userInfo.setDescription("这是个性签名");
    userInfo.setPhone("123456789");
    userInfo.setAvatar(loadFileTOByteArray(":/resource/image/groupAvatar.png"));   //此处需要把QIcon对象转化成二进制数据,进行传输
    pbResq.setUserInfo(userInfo);

    QByteArray body = pbResq.serialize(&serializer);

    //构造HTTP的响应
    //HTTP服务器这里的API和HTTP客户端这里的API,设计风格有明显差别
    QHttpServerResponse httpResp(body,QHttpServerResponse::StatusCode::Ok); //设置body
    httpResp.setHeader("Content-Type","application/x-protobuf");    //设置请求的内容类型
    return httpResp;
}

//获取好友列表
QHttpServerResponse HttpServer::getFriendList(const QHttpServerRequest &req)
{
    //解析请求,把req的body拿出来
    bite_im::GetFriendListReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG() << "[REQ 获取好友列表] requesId=" << pbReq.requestId() << ",loginSessionId=" << pbReq.sessionId();
    //构造响应
    bite_im::GetFriendListRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");

    //构造假数据
    //从文件读取数据的操作,是比较耗时的(读取硬盘)-->耗时操作放在循环内部,会使整个响应处理时间更长
    QByteArray avatar = loadFileTOByteArray(":/resource/image/defaultAvatar.png");
    for(int i = 0 ; i < 20 ; ++i){
        bite_im::UserInfo userInfo = makeUserInfo(i,avatar);
        //设置userInfo中的值
        pbResp.friendList().push_back(userInfo);
    }

    //进行序列化
    QByteArray body = pbResp.serialize(&serializer);

    //构造HTTP响应对象
    QHttpServerResponse httpResp(body,QHttpServerResponse::StatusCode::Ok);
    httpResp.setHeader("Content-Type","application/x-protobuf");
    return httpResp;
}

//获取会话列表
QHttpServerResponse HttpServer::getChatSessionList(const QHttpServerRequest &req)
{
    //解析请求,把req的body拿出来
    bite_im::GetChatSessionListReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG() << "[REQ 获取会话列表] requesId=" << pbReq.requestId() << ",loginSessionId=" << pbReq.sessionId();

    //构造响应
    bite_im::GetChatSessionListRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");

    //构造假数据
    //从文件读取数据的操作,是比较耗时的(读取硬盘)-->耗时操作放在循环内部,会使整个响应处理时间更长
    //构造干个单聊会话
    QByteArray avatar = loadFileTOByteArray(":/resource/image/defaultAvatar.png");
    for(int i = 0 ; i < 30 ; ++i){
        bite_im::ChatSessionInfo chatSessionInfo;
        chatSessionInfo.setChatSessionId(QString::number(2000 + i));
        chatSessionInfo.setChatSessionName("会话" + QString::number(i));
        chatSessionInfo.setSingleChatFriendId(QString::number(1000 + i));
        chatSessionInfo.setAvatar(avatar);

        //设置会话中的最后一条消息
        bite_im::MessageInfo messageInfo = makeTextMessageInfo(i,chatSessionInfo.chatSessionId(),avatar);   //构建文本消息
        chatSessionInfo.setPrevMessage(messageInfo);
        pbResp.chatSessionInfoList().push_back(chatSessionInfo);
    }

    //构造一个群聊对话
    QByteArray groupAvatar = loadFileTOByteArray(":/resource/image/groupAvatar.png");
    bite_im::ChatSessionInfo chatSessionInfo;
    chatSessionInfo.setChatSessionId(QString::number(2100));
    chatSessionInfo.setChatSessionName("会话" + QString::number(2100));
    chatSessionInfo.setSingleChatFriendId("");
    chatSessionInfo.setAvatar(groupAvatar);
    bite_im::MessageInfo messageInfo = makeTextMessageInfo(0,chatSessionInfo.chatSessionId(),avatar);   //构建文本消息
    chatSessionInfo.setPrevMessage(messageInfo);
    pbResp.chatSessionInfoList().push_back(chatSessionInfo);


    //进行序列化
    QByteArray body = pbResp.serialize(&serializer);

    //构造HTTP响应对象
    QHttpServerResponse httpResp(body,QHttpServerResponse::StatusCode::Ok);
    httpResp.setHeader("Content-Type","application/x-protobuf");
    return httpResp;
}

//获取好友申请列表
QHttpServerResponse HttpServer::getApplyList(const QHttpServerRequest &req)
{
    //解析请求,把req的body拿出来
    bite_im::GetPendingFriendEventListReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG() << "[REQ 获取会话列表] requesId=" << pbReq.requestId() << ",loginSessionId=" << pbReq.sessionId();

    //构造响应
    bite_im::GetPendingFriendEventListRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");

    //构造假数据-->循环构造出event对象,构造整个结果数组
    //从文件读取数据的操作,是比较耗时的(读取硬盘)-->耗时操作放在循环内部,会使整个响应处理时间更长
    QByteArray avatar = loadFileTOByteArray(":/resource/image/defaultAvatar.png");
    for(int i = 0 ; i < 5 ; ++i){
        bite_im::FriendEvent friendEvent;
        friendEvent.setEventId("");//此处不再使用EventId,直接设置为""
        friendEvent.setSender(makeUserInfo(i,avatar));

        pbResp.event().push_back(friendEvent);
    }

    //进行序列化
    QByteArray body = pbResp.serialize(&serializer);

    //构造HTTP响应对象
    QHttpServerResponse httpResp(body,QHttpServerResponse::StatusCode::Ok);
    httpResp.setHeader("Content-Type","application/x-protobuf");
    return httpResp;

}

//获取指定会话的最近历史消息列表
QHttpServerResponse HttpServer::getRecent(const QHttpServerRequest &req)
{
    //解析请求,把req的body拿出来
    bite_im::GetRecentMsgReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG() << "[REQ 获取最近消息列表] requesId=" << pbReq.requestId() << ",loginSessionId=" << pbReq.sessionId() << ",chatSessionId=" << pbReq.chatSessionId();

    //构造响应
    bite_im::GetRecentMsgRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");

    //构造假数据-->循环构造出messageInfo对象,构造整个结果数组
    //从文件读取数据的操作,是比较耗时的(读取硬盘)-->耗时操作放在循环内部,会使整个响应处理时间更长
    QByteArray avatar = loadFileTOByteArray(":/resource/image/defaultAvatar.png");
    for(int i = 0 ; i < 30 ; ++i){
        bite_im::MessageInfo messageInfo = makeTextMessageInfo(i,"2000",avatar);
        pbResp.msgList().push_back(messageInfo);
    }
    //图片消息
    bite_im::MessageInfo imageMessageInfo = makeImageMessageInfo(30,"2000",avatar);
    pbResp.msgList().push_back(imageMessageInfo);
    //文件消息
    bite_im::MessageInfo fileMessageInfo = makeFileMessageInfo(31,"2000",avatar);
    pbResp.msgList().push_back(fileMessageInfo);
    //语音消息
    bite_im::MessageInfo speechMessageInfo = makeSpeechMessageInfo(32,"2000",avatar);
    pbResp.msgList().push_back(speechMessageInfo);

    //进行序列化
    QByteArray body = pbResp.serialize(&serializer);

    //构造HTTP响应对象
    QHttpServerResponse httpResp(body,QHttpServerResponse::StatusCode::Ok);
    httpResp.setHeader("Content-Type","application/x-protobuf");
    return httpResp;
}

//处理从客户端发送消息
QHttpServerResponse HttpServer::newMessage(const QHttpServerRequest &req)
{
    //解析请求,把req的body拿出来
    bite_im::NewMessageReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG() << "[REQ 发送消息] requesId=" << pbReq.requestId() << ",loginSessionId=" << pbReq.sessionId() << ",chatSessionId=" << pbReq.chatSessionId() << ",massageType=" << pbReq.message().messageType();

    if(pbReq.message().messageType() == bite_im::MessageTypeGadget::MessageType::STRING){
        LOG() << "发送的消息内容=" << pbReq.message().stringMessage().content();
    }

    //构造响应
    bite_im::NewMessageRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");

    //进行序列化
    QByteArray body = pbResp.serialize(&serializer);

    //构造HPPT响应
    QHttpServerResponse resp(body,QHttpServerResponse::StatusCode::Ok);
    resp.setHeader("Content-Type","application/x-protobuf");
    return resp;
}

//处理修改个人信息的昵称
QHttpServerResponse HttpServer::setNickname(const QHttpServerRequest &req)
{
    //解析请求,把req的body拿出来
    bite_im::SetUserNicknameReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG() << "[REQ 修改用户昵称] requesId=" << pbReq.requestId() << ",loginSessionId=" << pbReq.sessionId() << ",nickname=" << pbReq.nickname();

    //构造响应
    bite_im::SetUserNicknameRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");

    //进行序列化
    QByteArray body = pbResp.serialize(&serializer);

    //构造HPPT响应
    QHttpServerResponse resp(body,QHttpServerResponse::StatusCode::Ok);
    resp.setHeader("Content-Type","application/x-protobuf");
    return resp;
}

//处理修改个人信息的个性签名
QHttpServerResponse HttpServer::setDescription(const QHttpServerRequest &req)
{
    //解析请求,把req的body拿出来
    bite_im::SetUserDescriptionReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG() << "[REQ 修改用户个性签名] requesId=" << pbReq.requestId() << ",loginSessionId=" << pbReq.sessionId() << ",description=" << pbReq.description();

    //构造响应
    bite_im::SetUserDescriptionRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");

    //进行序列化
    QByteArray body = pbResp.serialize(&serializer);

    //构造HPPT响应
    QHttpServerResponse resp(body,QHttpServerResponse::StatusCode::Ok);
    resp.setHeader("Content-Type","application/x-protobuf");
    return resp;
}

//处理获取短信验证码
QHttpServerResponse HttpServer::getPhoneVerifyCode(const QHttpServerRequest &req)
{
    //解析请求,把req的body拿出来
    bite_im::PhoneVerifyCodeReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG() << "[REQ 获取短信验证码] requesId=" << pbReq.requestId() << ",phone=" << pbReq.phoneNumber();

    //构造响应
    bite_im::PhoneVerifyCodeRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");
    pbResp.setVerifyCodeId("testVerifyCodeId");

    //进行序列化
    QByteArray body = pbResp.serialize(&serializer);

    //构造HPPT响应
    QHttpServerResponse resp(body,QHttpServerResponse::StatusCode::Ok);
    resp.setHeader("Content-Type","application/x-protobuf");
    return resp;
}

//处理修改个人信息的手机号
QHttpServerResponse HttpServer::setPhone(const QHttpServerRequest &req)
{
    //解析请求,把req的body拿出来
    bite_im::SetUserPhoneNumberReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG() << "[REQ 修改手机号] requesId=" << pbReq.requestId() << ",loginSessionId=" << pbReq.sessionId()
          << ",verfyCodeId=" << pbReq.phoneVerifyCodeId() << ",verifyCode" << pbReq.phoneVerifyCode() << ",phone=" << pbReq.phoneNumber();

    //构造响应
    bite_im::SetUserPhoneNumberRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");

    //进行序列化
    QByteArray body = pbResp.serialize(&serializer);

    //构造HPPT响应
    QHttpServerResponse resp(body,QHttpServerResponse::StatusCode::Ok);
    resp.setHeader("Content-Type","application/x-protobuf");
    return resp;
}

//处理修改个人信息的头像
QHttpServerResponse HttpServer::setAvatar(const QHttpServerRequest &req)
{
    //解析请求,把req的body拿出来
    bite_im::SetUserAvatarReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG() << "[REQ 修改头像] requesId=" << pbReq.requestId() << ",loginSessionId=" << pbReq.sessionId();

    //构造响应
    bite_im::SetUserAvatarRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");

    //进行序列化
    QByteArray body = pbResp.serialize(&serializer);

    //构造HPPT响应
    QHttpServerResponse resp(body,QHttpServerResponse::StatusCode::Ok);
    resp.setHeader("Content-Type","application/x-protobuf");
    return resp;
}

//处理删除好友
QHttpServerResponse HttpServer::removeFriend(const QHttpServerRequest &req)
{
    //解析请求,把req的body拿出来
    bite_im::FriendRemoveReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG() << "[REQ 删除好友] requesId=" << pbReq.requestId() << ",loginSessionId=" << pbReq.sessionId();

    //构造响应
    bite_im::FriendRemoveRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");

    //进行序列化
    QByteArray body = pbResp.serialize(&serializer);

    //构造HPPT响应
    QHttpServerResponse resp(body,QHttpServerResponse::StatusCode::Ok);
    resp.setHeader("Content-Type","application/x-protobuf");
    return resp;
}

//处理添加好友申请
QHttpServerResponse HttpServer::addFriendApply(const QHttpServerRequest &req)
{
    //解析请求,把req的body拿出来
    bite_im::FriendAddReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG() << "[REQ 添加好友申请] requesId=" << pbReq.requestId() << ",loginSessionId=" << pbReq.sessionId() << ",userId=" << pbReq.respondentId();

    //构造响应
    bite_im::FriendAddRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");
    pbResp.setNotifyEventId("");

    //进行序列化
    QByteArray body = pbResp.serialize(&serializer);

    //构造HPPT响应
    QHttpServerResponse resp(body,QHttpServerResponse::StatusCode::Ok);
    resp.setHeader("Content-Type","application/x-protobuf");
    return resp;

}

//对添加好友申请的处理
QHttpServerResponse HttpServer::addFriendProcess(const QHttpServerRequest &req)
{
    //解析请求,把req的body拿出来
    bite_im::FriendAddProcessReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG() << "[REQ 添加好友申请处理] requesId=" << pbReq.requestId() << ",loginSessionId=" << pbReq.sessionId() << ",userId=" << pbReq.applyUserId() << ",agree" << pbReq.agree();

    //构造响应
    bite_im::FriendAddProcessRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");
    pbResp.setNewSessionId("");

    //进行序列化
    QByteArray body = pbResp.serialize(&serializer);

    //构造HPPT响应
    QHttpServerResponse resp(body,QHttpServerResponse::StatusCode::Ok);
    resp.setHeader("Content-Type","application/x-protobuf");
    return resp;
}

//处理创建会话申请
QHttpServerResponse HttpServer::createChatSession(const QHttpServerRequest &req)
{
    //解析请求,把req的body拿出来
    bite_im::ChatSessionCreateReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG() << "[REQ 创建会话] requesId=" << pbReq.requestId() << ",loginSessionId=" << pbReq.sessionId() << ",userIdList=" << pbReq.memberIdList();

    //构造响应
    bite_im::ChatSessionCreateRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");

    //进行序列化
    QByteArray body = pbResp.serialize(&serializer);

    //构造HPPT响应
    QHttpServerResponse resp(body,QHttpServerResponse::StatusCode::Ok);
    resp.setHeader("Content-Type","application/x-protobuf");
    return resp;
}

//获取会话成员列表
QHttpServerResponse HttpServer::getChatSessionMember(const QHttpServerRequest &req)
{
    //解析请求,把req的body拿出来
    bite_im::GetChatSessionMemberReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG() << "[REQ 获取会话成员列表] requesId=" << pbReq.requestId() << ",loginSessionId=" << pbReq.sessionId() << ",chatSessionId=" << pbReq.chatSessionId();

    //构造响应
    bite_im::GetChatSessionMemberRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");

    //循环构造多个userInfo，添加到memberInfoList中
    QByteArray avatar = loadFileTOByteArray(":/resource/image/defaultAvatar.png");
    for(int i = 0 ; i < 10 ; ++i){
        bite_im::UserInfo userInfo = makeUserInfo(i,avatar);
        pbResp.memberInfoList().push_back(userInfo);
    }

    //进行序列化
    QByteArray body = pbResp.serialize(&serializer);

    //构造HPPT响应
    QHttpServerResponse resp(body,QHttpServerResponse::StatusCode::Ok);
    resp.setHeader("Content-Type","application/x-protobuf");
    return resp;

}

//获取搜索用户结果
QHttpServerResponse HttpServer::searchFriend(const QHttpServerRequest &req)
{
    //解析请求,把req的body拿出来
    bite_im::FriendSearchReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG() << "[REQ 搜索用户] requesId=" << pbReq.requestId() << ",loginSessionId=" << pbReq.sessionId() << ",searchKey=" << pbReq.searchKey();

    //构造响应
    bite_im::FriendSearchRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");

    //循环构造多个userInfo，添加到memberInfoList中
    QByteArray avatar = loadFileTOByteArray(":/resource/image/defaultAvatar.png");
    for(int i = 0 ; i < 30 ; ++i){
        bite_im::UserInfo userInfo = makeUserInfo(i,avatar);
        pbResp.userInfo().push_back(userInfo);
    }

    //进行序列化
    QByteArray body = pbResp.serialize(&serializer);

    //构造HPPT响应
    QHttpServerResponse resp(body,QHttpServerResponse::StatusCode::Ok);
    resp.setHeader("Content-Type","application/x-protobuf");
    return resp;

}

//获取搜索历史消息结果
QHttpServerResponse HttpServer::searchHistory(const QHttpServerRequest &req)
{
    //解析请求,把req的body拿出来
    bite_im::MsgSearchReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG() << "[REQ 搜索历史消息] requesId=" << pbReq.requestId() << ",loginSessionId=" << pbReq.sessionId() << ",chatSessionId=" << pbReq.chatSessionId() << ",searchKey=" << pbReq.searchKey();

    //构造响应
    bite_im::MsgSearchRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");

    //循环构造多个消息对象,并返回
    QByteArray avatar = loadFileTOByteArray(":/resource/image/defaultAvatar.png");
    for(int i = 0 ; i < 10 ; ++i){
        bite_im::MessageInfo message = makeTextMessageInfo(i,pbReq.chatSessionId(),avatar);
        pbResp.msgList().push_back(message);
    }
    //图片消息
    bite_im::MessageInfo imageMessage = makeImageMessageInfo(10,pbReq.chatSessionId(),avatar);
    pbResp.msgList().push_back(imageMessage);
    //文件消息
    bite_im::MessageInfo fileMessage = makeFileMessageInfo(11,pbReq.chatSessionId(),avatar);
    pbResp.msgList().push_back(fileMessage);
    //语音消息
    bite_im::MessageInfo speechMessage = makeSpeechMessageInfo(12,pbReq.chatSessionId(),avatar);
    pbResp.msgList().push_back(speechMessage);

    //进行序列化
    QByteArray body = pbResp.serialize(&serializer);

    //构造HPPT响应
    QHttpServerResponse resp(body,QHttpServerResponse::StatusCode::Ok);
    resp.setHeader("Content-Type","application/x-protobuf");
    return resp;

}

//获取按时间搜索历史消息结果
QHttpServerResponse HttpServer::getHistory(const QHttpServerRequest &req)
{
    //解析请求,把req的body拿出来
    bite_im::GetHistoryMsgReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG() << "[REQ 按时间搜索历史消息] requesId=" << pbReq.requestId() << ",loginSessionId=" << pbReq.sessionId() << ",chatSessionId=" << pbReq.chatSessionId() << ",beginTime=" << pbReq.startTime() << ",endTime=" << pbReq.overTime();

    //构造响应
    bite_im::GetHistoryMsgRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");

    //循环构造多个消息对象,并返回
    QByteArray avatar = loadFileTOByteArray(":/resource/image/defaultAvatar.png");
    for(int i = 0 ; i < 10 ; ++i){
        bite_im::MessageInfo message = makeTextMessageInfo(i,pbReq.chatSessionId(),avatar);
        pbResp.msgList().push_back(message);
    }

    //进行序列化
    QByteArray body = pbResp.serialize(&serializer);

    //构造HPPT响应
    QHttpServerResponse resp(body,QHttpServerResponse::StatusCode::Ok);
    resp.setHeader("Content-Type","application/x-protobuf");
    return resp;
}

//用户名登录请求
QHttpServerResponse HttpServer::usernameLogin(const QHttpServerRequest &req)
{
    //解析请求,把req的body拿出来
    bite_im::UserLoginReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG() << "[REQ 用户名密码登录] requesId=" << pbReq.requestId()<< ",username=" << pbReq.nickname() << ",possword=" << pbReq.password();

    //构造响应
    bite_im::UserLoginRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");
    pbResp.setLoginSessionId("testLoginSessionId");

    //进行序列化
    QByteArray body = pbResp.serialize(&serializer);

    //构造HPPT响应
    QHttpServerResponse resp(body,QHttpServerResponse::StatusCode::Ok);
    resp.setHeader("Content-Type","application/x-protobuf");
    return resp;
}

//用户名注册请求
QHttpServerResponse HttpServer::usernameRegister(const QHttpServerRequest &req)
{
    //解析请求,把req的body拿出来
    bite_im::UserRegisterReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG() << "[REQ 用户名密码登录] requesId=" << pbReq.requestId()<< ",username=" << pbReq.nickname() << ",possword=" << pbReq.password();

    //构造响应
    bite_im::UserRegisterRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");

    //进行序列化
    QByteArray body = pbResp.serialize(&serializer);

    //构造HPPT响应
    QHttpServerResponse resp(body,QHttpServerResponse::StatusCode::Ok);
    resp.setHeader("Content-Type","application/x-protobuf");
    return resp;

}

//电话登录请求
QHttpServerResponse HttpServer::phoneLogin(const QHttpServerRequest &req)
{
    //解析请求,把req的body拿出来
    bite_im::PhoneLoginReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG() << "[REQ 手机号登录] requesId=" << pbReq.requestId()<< ",phone=" << pbReq.phoneNumber() << ",verifyCodeId=" << pbReq.verifyCodeId() << ",verifyCode=" << pbReq.verifyCode();

    //构造响应
    bite_im::PhoneLoginRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");
    pbResp.setLoginSessionId("testLoginSessionId");

    //进行序列化
    QByteArray body = pbResp.serialize(&serializer);

    //构造HPPT响应
    QHttpServerResponse resp(body,QHttpServerResponse::StatusCode::Ok);
    resp.setHeader("Content-Type","application/x-protobuf");
    return resp;
}

//用户名注册请求
QHttpServerResponse HttpServer::phoneRegister(const QHttpServerRequest &req)
{
    //解析请求,把req的body拿出来
    bite_im::PhoneRegisterReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG() << "[REQ 手机号注册] requesId=" << pbReq.requestId()<< ",phone=" << pbReq.phoneNumber() << ",verifyCodeId=" << pbReq.verifyCodeId() << ",verifyCode=" << pbReq.verifyCode();

    //构造响应
    bite_im::PhoneRegisterRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");

    //进行序列化
    QByteArray body = pbResp.serialize(&serializer);

    //构造HPPT响应
    QHttpServerResponse resp(body,QHttpServerResponse::StatusCode::Ok);
    resp.setHeader("Content-Type","application/x-protobuf");
    return resp;
}

//获取单个文件
QHttpServerResponse HttpServer::getSingleFile(const QHttpServerRequest &req)
{
    //解析请求,把req的body拿出来
    bite_im::GetSingleFileReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG() << "[REQ 获取单个文件] requesId=" << pbReq.requestId()<< ",fileId=" << pbReq.fileId();

    //构造响应
    bite_im::GetSingleFileRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");

    bite_im::FileDownloadData fileDownloadData;
    fileDownloadData.setFileId(pbReq.fileId());
    //此处后续能够支持三种情况,图片文件,普通文件,语音文件
    //直接使用fileId做区分
    if(pbReq.fileId() == "testImage"){
        //fileDownloadData.setFileContent(loadFileTOByteArray(":/resource/image/logo.png"));
        fileDownloadData.setFileContent(loadFileTOByteArray(":/resource/image/defaultAvatar.png"));
    } else if (pbReq.fileId() == "testFile") {
        fileDownloadData.setFileContent(loadFileTOByteArray(":/resource/file/test.txt"));
    } else if (pbReq.fileId() == "testSpeech") {
        //由于此时还没有音频文件，得后面写了 录音功能 才能生成
        fileDownloadData.setFileContent(loadFileTOByteArray(":/resource/file/speech.pcm"));
    } else {
        pbResp.setSuccess(false);
        pbResp.setErrmsg("fileId不是预期的测试 fileId");
    }
    pbResp.setFileData(fileDownloadData);

    //进行序列化
    QByteArray body = pbResp.serialize(&serializer);

    //构造HPPT响应
    QHttpServerResponse resp(body,QHttpServerResponse::StatusCode::Ok);
    resp.setHeader("Content-Type","application/x-protobuf");
    return resp;
}

//语音转文字
QHttpServerResponse HttpServer::recognition(const QHttpServerRequest &req)
{
    //解析请求,把req的body拿出来
    bite_im::SpeechRecognitionReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG() << "[REQ 语音转文字] requesId=" << pbReq.requestId() << ",loginSessionId=" << pbReq.sessionId();

    //构造响应
    bite_im::SpeechRecognitionRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");
    pbResp.setRecognitionResult("你好，你好,这是语音消息");

    //进行序列化
    QByteArray body = pbResp.serialize(&serializer);

    //构造HPPT响应
    QHttpServerResponse resp(body,QHttpServerResponse::StatusCode::Ok);
    resp.setHeader("Content-Type","application/x-protobuf");
    return resp;

}

/////////////////////////////////////////////////////////////////////////////////////
/// Websocket 服务器
/////////////////////////////////////////////////////////////////////////////////////

//初始化instance
WebsocketServer* WebsocketServer::instance = nullptr;

//获取实例
WebsocketServer *WebsocketServer::getInstance()
{
    if(instance == nullptr){
        instance = new WebsocketServer();
    }
    return instance;
}

//初始化WebsocketServer(Websocket服务器)-->连接信号槽,绑定端口......
bool WebsocketServer::init()
{
    //1.连接信号槽
    connect(&websocketServer,&QWebSocketServer::newConnection,this,[=](){
        //连接建立成功之后
        qDebug() << "[websocket] 连接建立成功!";

        //获取到用来通信的socket对象,nextPendingConnection() 类似于 原生socket中的accept
        QWebSocket* socket = websocketServer.nextPendingConnection();

        //针对这个socket对象,来进行后续信号(剩余信号)的处理
        connect(socket,&QWebSocket::disconnected,this,[=](){
            qDebug() << "[websocket] 连接断开！";
            disconnect(this,&WebsocketServer::sendTextResp,this,nullptr);
            disconnect(this,&WebsocketServer::sendImageResp,this,nullptr);
            disconnect(this,&WebsocketServer::sendFileResp,this,nullptr);
            disconnect(this,&WebsocketServer::sendSpeechResp,this,nullptr);
            disconnect(this,&WebsocketServer::sendFriendRemove,this,nullptr);
            disconnect(this,&WebsocketServer::sendAddFriendApply,this,nullptr);
            disconnect(this,&WebsocketServer::sendAddFriendProcess,this,nullptr);
            disconnect(this,&WebsocketServer::sendCreateChatSession,this,nullptr);
        });

        connect(socket,&QWebSocket::errorOccurred,this,[=](QAbstractSocket::SocketError error){
            qDebug() << "[websocket] 连接出错！" << error;
        });

        connect(socket,&QWebSocket::textMessageReceived,this,[=](const QString& message){
            qDebug() << "[websocket] 收到文本数据！" << message;
        });

        connect(socket,&QWebSocket::binaryMessageReceived,this,[=](const QByteArray& byteArray){
            qDebug() << "[websocket] 收到二进制数据！" << byteArray.length();
        });


        //正常来说,释放对象,信号槽是disconnect,之前的代码中基本很少手动disconnect
        //由于此处信号槽,是连接this和this,和socket对象无关,释放socket对象,不会影响到上述信号
        //这个信号槽连接后,在断开连接时,要自动手动释放-->确保断开连接时,在做发送文本消息时,不做处理,防止野指针(socket在断开连接后,指向一个无效的对象)
        //                                     -->确保客户端断开连接,再次重新连接时,不会触发程序崩溃问题
        //发送文本消息
        connect(this,&WebsocketServer::sendTextResp,this,[=](){
            //此处就可以捕获到socket对象,从而可以通过socket对象给客户端返回数据
            if(socket == nullptr || !socket->isValid()){
                LOG() << "socket 对象无效!";
                return;
            }
            //构造响应数据
            QByteArray avatar = loadFileTOByteArray(":/resource/image/defaultAvatar.png");
            bite_im::MessageInfo messageInfo = makeTextMessageInfo(this->messageIndex++,"2000",avatar);

            bite_im::NotifyNewMessage notifyNewMessage;
            notifyNewMessage.setMessageInfo(messageInfo);

            bite_im::NotifyMessage notifyMessage;
            notifyMessage.setNotifyEventId("");
            notifyMessage.setNotifyType(bite_im::NotifyTypeGadget::NotifyType::CHAT_MESSAGE_NOTIFY);
            notifyMessage.setNewMessageInfo(notifyNewMessage);

            //序列化
            QByteArray body = notifyMessage.serialize(&this->serializer);

            //发送消息给客户端
            socket->sendBinaryMessage(body);

            LOG() << "发送文本消息响应:" << messageInfo.message().stringMessage().content();
        });

        //发送图片消息
        connect(this,&WebsocketServer::sendImageResp,this,[=](){
            //此处就可以捕获到socket对象,从而可以通过socket对象给客户端返回数据
            if(socket == nullptr || !socket->isValid()){
                LOG() << "socket 对象无效!";
                return;
            }
            //构造响应数据
            QByteArray avatar = loadFileTOByteArray(":/resource/image/defaultAvatar.png");
            bite_im::MessageInfo messageInfo = makeImageMessageInfo(this->messageIndex++,"2000",avatar);

            bite_im::NotifyNewMessage notifyNewMessage;
            notifyNewMessage.setMessageInfo(messageInfo);

            bite_im::NotifyMessage notifyMessage;
            notifyMessage.setNotifyEventId("");
            notifyMessage.setNotifyType(bite_im::NotifyTypeGadget::NotifyType::CHAT_MESSAGE_NOTIFY);
            notifyMessage.setNewMessageInfo(notifyNewMessage);

            //序列化
            QByteArray body = notifyMessage.serialize(&this->serializer);

            //发送消息给客户端
            socket->sendBinaryMessage(body);

            LOG() << "发送图片消息响应";
        });

        //发送文件消息
        connect(this,&WebsocketServer::sendFileResp,this,[=](){
            //此处就可以捕获到socket对象,从而可以通过socket对象给客户端返回数据
            if(socket == nullptr || !socket->isValid()){
                LOG() << "socket 对象无效!";
                return;
            }
            //构造响应数据
            QByteArray avatar = loadFileTOByteArray(":/resource/image/defaultAvatar.png");
            bite_im::MessageInfo messageInfo = makeFileMessageInfo(this->messageIndex++,"2000",avatar);

            bite_im::NotifyNewMessage notifyNewMessage;
            notifyNewMessage.setMessageInfo(messageInfo);

            bite_im::NotifyMessage notifyMessage;
            notifyMessage.setNotifyEventId("");
            notifyMessage.setNotifyType(bite_im::NotifyTypeGadget::NotifyType::CHAT_MESSAGE_NOTIFY);
            notifyMessage.setNewMessageInfo(notifyNewMessage);

            //序列化
            QByteArray body = notifyMessage.serialize(&this->serializer);

            //发送消息给客户端
            socket->sendBinaryMessage(body);

            LOG() << "发送文件消息响应";
        });


        //发送语音消息
        connect(this,&WebsocketServer::sendSpeechResp,this,[=](){
            //此处就可以捕获到socket对象,从而可以通过socket对象给客户端返回数据
            if(socket == nullptr || !socket->isValid()){
                LOG() << "socket 对象无效!";
                return;
            }
            //构造响应数据
            QByteArray avatar = loadFileTOByteArray(":/resource/image/defaultAvatar.png");
            bite_im::MessageInfo messageInfo = makeSpeechMessageInfo(this->messageIndex++,"2000",avatar);

            bite_im::NotifyNewMessage notifyNewMessage;
            notifyNewMessage.setMessageInfo(messageInfo);

            bite_im::NotifyMessage notifyMessage;
            notifyMessage.setNotifyEventId("");
            notifyMessage.setNotifyType(bite_im::NotifyTypeGadget::NotifyType::CHAT_MESSAGE_NOTIFY);
            notifyMessage.setNewMessageInfo(notifyNewMessage);

            //序列化
            QByteArray body = notifyMessage.serialize(&this->serializer);

            //发送消息给客户端
            socket->sendBinaryMessage(body);

            LOG() << "发送语音消息响应";
        });

        //这个信号槽连接后,在断开连接时,要自动手动释放-->确保断开连接时,在做发送文本消息时,不做处理,防止野指针(socket在断开连接后,指向一个无效的对象)
        //                                     -->确保客户端断开连接,再次重新连接时,不会触发程序崩溃问题
        connect(this,&WebsocketServer::sendFriendRemove,this,[=](){
            if(socket == nullptr || !socket->isValid()){
                LOG() << "socket对象无效";
                return;
            }

            //构造响应数据
            bite_im::NotifyMessage notifyMessage;
            notifyMessage.setNotifyEventId("");
            notifyMessage.setNotifyType(bite_im::NotifyTypeGadget::NotifyType::FRIEND_REMOVE_NOTIFY);

            bite_im::NotifyFriendRemove notifyFriendRemove;
            notifyFriendRemove.setUserId("1000");
            notifyMessage.setFriendRemove(notifyFriendRemove);

            //序列化
            QByteArray body = notifyMessage.serialize(&serializer);

            //发送消息给客户端
            socket->sendBinaryMessage(body);

            LOG() << "通知对方好友被删除了 userId=1000";
        });

        connect(this,&WebsocketServer::sendAddFriendApply,this,[=](){
            if(socket == nullptr || !socket->isValid()){
                LOG() << "socket对象无效";
                return;
            }

            //构造响应数据
            bite_im::NotifyMessage notifyMessage;
            notifyMessage.setNotifyEventId("");
            notifyMessage.setNotifyType(bite_im::NotifyTypeGadget::NotifyType::FRIEND_ADD_APPLY_NOTIFY);

            QByteArray avatar = loadFileTOByteArray(":/resource/image/defaultAvatar.png");
            bite_im::UserInfo userInfo = makeUserInfo(100,avatar);

            bite_im::NotifyFriendAddApply friendAddApply;
            friendAddApply.setUserInfo(userInfo);

            notifyMessage.setFriendAddApply(friendAddApply);

            //序列化
            QByteArray body = notifyMessage.serialize(&serializer);

            //发送消息给客户端
            socket->sendBinaryMessage(body);

            LOG() << "通知对方好友申请数据";
        });

        connect(this,&WebsocketServer::sendAddFriendProcess,this,[=](bool agree){
            if(socket == nullptr || !socket->isValid()){
                LOG() << "socket对象无效";
                return;
            }

            //构造响应数据
            bite_im::NotifyMessage notifyMessage;
            notifyMessage.setNotifyEventId("");
            notifyMessage.setNotifyType(bite_im::NotifyTypeGadget::NotifyType::FRIEND_ADD_PROCESS_NOTIFY);

            QByteArray avatar = loadFileTOByteArray(":/resource/image/defaultAvatar.png");
            bite_im::UserInfo userInfo = makeUserInfo(100,avatar);

            bite_im::NotifyFriendAddProcess friendAddProcess;
            friendAddProcess.setUserInfo(userInfo);
            friendAddProcess.setAgree(agree);

            notifyMessage.setFriendProcessResult(friendAddProcess);

            //序列化
            QByteArray body = notifyMessage.serialize(&serializer);

            //发送消息给客户端
            socket->sendBinaryMessage(body);

            LOG() << "通知好友申请的处理结果,userId=" << userInfo.userId() << ",agree=" << agree;
        });

        connect(this,&WebsocketServer::sendCreateChatSession,this,[=](){
            if(socket == nullptr || !socket->isValid()){
                LOG() << "socket对象无效";
                return;
            }

            //构造响应数据
            bite_im::NotifyMessage notifyMessage;
            notifyMessage.setNotifyEventId("");
            notifyMessage.setNotifyType(bite_im::NotifyTypeGadget::NotifyType::CHAT_SESSION_CREATE_NOTIFY);


            QByteArray avatar = loadFileTOByteArray(":/resource/image/groupAvatar.png");
            bite_im::MessageInfo messageInfo = makeTextMessageInfo(0,"2100",avatar);

            bite_im::ChatSessionInfo chatSessionInfo;
            chatSessionInfo.setChatSessionId("2100");
            chatSessionInfo.setSingleChatFriendId("");
            chatSessionInfo.setChatSessionName("新的群聊");
            chatSessionInfo.setPrevMessage(messageInfo);
            chatSessionInfo.setAvatar(avatar);

            bite_im::NotifyNewChatSession newChatSession;
            newChatSession.setChatSessionInfo(chatSessionInfo);
            notifyMessage.setNewChatSessionInfo(newChatSession);

            //序列化
            QByteArray body = notifyMessage.serialize(&serializer);

            //发送消息给客户端
            socket->sendBinaryMessage(body);

            LOG() << "通知创建会话" ;
        });
    });

    //2.绑定端口,启动服务-->直接返回是否绑定成功
    bool ok = websocketServer.listen(QHostAddress::Any,8001);

    return ok;
}
